/**
 * EDA分析页面JavaScript模块
 * 负责处理EDA数据分析的前端逻辑
 */

// EDA分析配置
const EDAAnalysisConfig = {
    // 列分类定义
    columnCategories: {
        'basic': [
            { prop: 'fileName', label: '文件名', width: 200, sortable: true, category: 'basic' },
            { prop: 'dataPoints', label: '数据点数', width: 120, sortable: true, category: 'basic' },
            { prop: 'duration', label: '记录时长(min)', width: 140, sortable: true, category: 'basic' },
            { prop: 'samplingRate', label: '采样率(Hz)', width: 120, sortable: true, category: 'basic' }
        ],
        'eda_stats': [
            { prop: 'meanEDA', label: '平均EDA(μS)', width: 130, sortable: true, category: 'eda_stats' },
            { prop: 'stdEDA', label: 'EDA标准差(μS)', width: 140, sortable: true, category: 'eda_stats' },
            { prop: 'minEDA', label: 'EDA最小值(μS)', width: 130, sortable: true, category: 'eda_stats' },
            { prop: 'maxEDA', label: 'EDA最大值(μS)', width: 130, sortable: true, category: 'eda_stats' },
            { prop: 'rangeEDA', label: 'EDA范围(μS)', width: 130, sortable: true, category: 'eda_stats' }
        ],
        'scr_peaks': [
            { prop: 'scrPeaks', label: 'SCR峰值数量', width: 130, sortable: true, category: 'scr_peaks' },
            { prop: 'meanSCRAmplitude', label: '平均SCR幅度(μS)', width: 150, sortable: true, category: 'scr_peaks' },
            { prop: 'maxSCRAmplitude', label: '最大SCR幅度(μS)', width: 150, sortable: true, category: 'scr_peaks' },
            { prop: 'meanSCRWidth', label: '平均SCR宽度(s)', width: 140, sortable: true, category: 'scr_peaks' },
            { prop: 'scrFrequency', label: 'SCR频率(次/min)', width: 140, sortable: true, category: 'scr_peaks' }
        ],
        'scl_baseline': [
            { prop: 'baselineLevel', label: '基线水平(μS)', width: 130, sortable: true, category: 'scl_baseline' },
            { prop: 'baselineStd', label: '基线标准差(μS)', width: 140, sortable: true, category: 'scl_baseline' },
            { prop: 'trendSlope', label: '趋势斜率', width: 120, sortable: true, category: 'scl_baseline' }
        ],
        'signal_quality': [
            { prop: 'signalQuality', label: '信号质量', width: 120, sortable: true, category: 'signal_quality' },
            { prop: 'snrDB', label: '信噪比(dB)', width: 120, sortable: true, category: 'signal_quality' },
            { prop: 'zeroRatio', label: '零值比例(%)', width: 130, sortable: true, category: 'signal_quality' },
            { prop: 'stabilityIndex', label: '稳定性指数', width: 130, sortable: true, category: 'signal_quality' }
        ],
        'statistical': [
            { prop: 'skewness', label: '偏度', width: 100, sortable: true, category: 'statistical' },
            { prop: 'kurtosis', label: '峰度', width: 100, sortable: true, category: 'statistical' }
        ],
        'frequency': [
            { prop: 'vlf_power', label: 'VLF功率', width: 120, sortable: true, category: 'frequency' },
            { prop: 'lf_power', label: 'LF功率', width: 120, sortable: true, category: 'frequency' },
            { prop: 'mf_power', label: 'MF功率', width: 120, sortable: true, category: 'frequency' },
            { prop: 'total_power', label: '总功率', width: 120, sortable: true, category: 'frequency' },
            { prop: 'vlf_ratio', label: 'VLF功率比(%)', width: 130, sortable: true, category: 'frequency' },
            { prop: 'lf_ratio', label: 'LF功率比(%)', width: 130, sortable: true, category: 'frequency' },
            { prop: 'mf_ratio', label: 'MF功率比(%)', width: 130, sortable: true, category: 'frequency' },
            { prop: 'peak_freq', label: '主频(Hz)', width: 120, sortable: true, category: 'frequency' }
        ]
    },

    // 默认显示的列
    defaultColumns: ['fileName', 'dataPoints', 'duration', 'meanEDA', 'stdEDA', 'scrPeaks', 'meanSCRAmplitude', 'signalQuality']
};

/**
 * 清理数据中的特殊数值，确保前端显示正常
 * @param {any} value - 待清理的数值
 * @returns {any} 清理后的数值
 */
function sanitizeValue(value) {
    if (typeof value === 'number') {
        if (isNaN(value)) {
            return null; // NaN转为null
        }
        if (!isFinite(value)) {
            return value > 0 ? 999999 : -999999; // Infinity转为边界值
        }
    }
    return value;
}

/**
 * 递归清理对象中的特殊数值
 * @param {Object} obj - 待清理的对象
 * @returns {Object} 清理后的对象
 */
function sanitizeObject(obj) {
    if (Array.isArray(obj)) {
        return obj.map(item => sanitizeObject(item));
    } else if (obj !== null && typeof obj === 'object') {
        const sanitized = {};
        for (const [key, value] of Object.entries(obj)) {
            sanitized[key] = sanitizeObject(value);
        }
        return sanitized;
    } else {
        return sanitizeValue(obj);
    }
}

// 创建Vue应用
function createEDAAnalysisApp() {
    const { createApp } = Vue;
    const { ElMessage, ElMessageBox } = ElementPlus;

    const app = createApp({
        data() {
            return {
                sidebarCollapsed: false,
                sidebarShow: true,

                // 文件管理相关
                fileList: [],
                isDragOver: false,
                currentTaskId: null,

                // 分析状态
                isAnalyzing: false,
                analysisProgress: 0,

                // 日志系统
                analysisLogs: [],
                logPanelCollapsed: false,
                logPollingTimer: null,  // 日志轮询定时器
                lastLogCount: 0,        // 上次获取的日志数量

                // 结果展示
                analysisResults: [],
                showColumnManager: false,
                selectedColumns: [],

                // 分析配置参数
                analysisConfig: {
                    sampleRate: 4,
                    algorithm: 'brainhorm'  // 默认使用BrainHorm算法
                },

                // 算法选项配置
                algorithmOptions: [
                    {
                        value: 'brainhorm',
                        label: 'BrainHorm',
                        description: '改进的EDA处理算法，支持自定义参数配置'
                    },
                    {
                        value: 'neurokit2', 
                        label: 'NeuroKit2',
                        description: '基于NeuroKit2库的标准EDA处理方法'
                    }
                ]
            }
        },

        computed: {
            // 所有可用的列定义
            allColumns() {
                const columns = [];
                Object.values(EDAAnalysisConfig.columnCategories).forEach(categoryColumns => {
                    columns.push(...categoryColumns);
                });
                return columns;
            },
            
            // 显示的列
            visibleColumns() {
                return this.allColumns.filter(col => this.selectedColumns.includes(col.prop));
            },
            
            // 按分类分组的列
            columnsByCategory() {
                return EDAAnalysisConfig.columnCategories;
            },
            
            // 分类名称映射
            categoryNames() {
                return {
                    'basic': '基本信息',
                    'eda_stats': 'EDA统计',
                    'scr_peaks': 'SCR峰值特征',
                    'scl_baseline': 'SCL基线指标',
                    'signal_quality': '信号质量指标',
                    'statistical': '统计特征',
                    'frequency': '频域分析'
                };
            },

            // 使用统一的图标配置
            ...window.IconsConfig.getIconsComputed()
        },

        methods: {
            // ========== UI控制方法 ==========
            toggleSidebar() {
                if (window.innerWidth <= 575) {
                    this.sidebarShow = !this.sidebarShow;
                } else {
                    this.sidebarCollapsed = !this.sidebarCollapsed;
                }
            },

            goHome() {
                window.location.href = '../index.html';
            },

            // ========== 文件管理方法 ==========
            triggerFileUpload() {
                this.$refs.fileInput.click();
            },

            async handleFileSelect(event) {
                const files = Array.from(event.target.files);
                await this.uploadFiles(files);
                event.target.value = '';
            },

            async handleDrop(event) {
                event.preventDefault();
                this.isDragOver = false;
                const files = Array.from(event.dataTransfer.files);
                await this.uploadFiles(files);
            },

            async uploadFiles(files) {
                const validFiles = files.filter(file => {
                    const isValidType = file.name.toLowerCase().endsWith('.txt') ||
                        file.name.toLowerCase().endsWith('.csv');
                    if (!isValidType) {
                        ElMessage.warning(`文件 ${file.name} 格式不支持，仅支持 .txt 和 .csv 格式`);
                        return false;
                    }

                    const isDuplicate = this.fileList.some(existingFile =>
                        existingFile.name === file.name && existingFile.size === file.size
                    );
                    if (isDuplicate) {
                        ElMessage.warning(`文件 ${file.name} 已存在`);
                        return false;
                    }

                    return true;
                });

                if (validFiles.length === 0) {
                    return;
                }

                try {
                    const formData = new FormData();
                    validFiles.forEach(file => {
                        formData.append('files', file);
                    });

                    this.addLog('info', `开始上传 ${validFiles.length} 个文件...`);

                    const response = await axios.post('/api/eda/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });

                    console.log('API响应:', response);
                    console.log('响应数据:', response.data);
                    console.log('success字段:', response.data.success);

                    if (response.data.success) {
                        this.currentTaskId = response.data.task_id;
                        
                        response.data.files.forEach(fileInfo => {
                            this.fileList.push({
                                id: Date.now() + Math.random(),
                                name: fileInfo.name,
                                size: fileInfo.size,
                                status: 'waiting',
                                progress: 0
                            });
                        });

                        this.addLog('success', `文件上传成功，任务ID: ${this.currentTaskId}`);
                        ElMessage.success(`成功上传 ${validFiles.length} 个文件`);
                    } else {
                        throw new Error(response.data.error || '上传失败');
                    }

                } catch (error) {
                    this.addLog('error', `文件上传失败: ${error.message}`);
                    ElMessage.error(`上传失败: ${error.message}`);
                }
            },

            removeFile(index) {
                const fileName = this.fileList[index].name;
                this.fileList.splice(index, 1);
                ElMessage.success(`已移除文件: ${fileName}`);
            },

            clearAllFiles() {
                ElMessageBox.confirm('确定要清空所有文件吗？', '确认操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.fileList = [];
                    this.analysisResults = [];
                    this.analysisLogs = [];
                    this.currentTaskId = null;
                    ElMessage.success('已清空所有文件');
                }).catch(() => { });
            },

            // ========== 分析引擎方法 ==========
            async startBatchAnalysis() {
                if (this.fileList.length === 0) {
                    ElMessage.warning('请先上传文件');
                    return;
                }

                if (!this.currentTaskId) {
                    ElMessage.error('没有有效的任务ID，请重新上传文件');
                    return;
                }

                this.isAnalyzing = true;
                this.analysisResults = [];
                this.clearLogs();
                this.addLog('info', '开始批量分析...');

                // 启动实时日志轮询
                await this.startLogPolling();

                try {
                    const response = await axios.post('/api/eda/analyze', {
                        task_id: this.currentTaskId,
                        config: {
                            sampleRate: this.analysisConfig.sampleRate,
                            algorithm: this.analysisConfig.algorithm
                        }
                    });

                    if (response.data.success) {
                        // 清理分析结果中的特殊数值
                        const sanitizedResults = sanitizeObject(response.data.results);
                        this.analysisResults = sanitizedResults;
                        
                        this.fileList.forEach(file => {
                            const result = this.analysisResults.find(r => r.fileName === file.name);
                            if (result) {
                                file.status = result.status === 'error' ? 'error' : 'completed';
                                file.progress = 100;
                            }
                        });

                        // 在添加完成日志前，先获取服务器的最终日志
                        if (this.currentTaskId) {
                            console.log('任务完成前获取最终服务器日志...');
                            await this.fetchRealtimeLogs();
                        }

                        this.addLog('success', `批量分析完成！共处理 ${this.analysisResults.length} 个文件`);
                        ElMessage.success('批量分析完成');
                    } else {
                        throw new Error(response.data.error || '分析失败');
                    }

                } catch (error) {
                    this.addLog('error', `分析过程中发生错误: ${error.message}`);
                    ElMessage.error(`分析失败: ${error.message}`);
                    
                    this.fileList.forEach(file => {
                        if (file.status === 'analyzing') {
                            file.status = 'error';
                        }
                    });
                } finally {
                    this.isAnalyzing = false;
                    // 停止实时日志轮询
                    await this.stopLogPolling();
                }
            },

            // ========== 日志系统方法 ==========
            addLog(type, message) {
                const timestamp = new Date().toLocaleTimeString();
                this.analysisLogs.push({
                    type: type,
                    message: message,
                    timestamp: timestamp
                });

                this.$nextTick(() => {
                    const logContainer = this.$refs.logContainer;
                    if (logContainer) {
                        logContainer.scrollTop = logContainer.scrollHeight;
                    }
                });
            },

            getLogClass(type) {
                return `log-${type}`;
            },

            clearLogs() {
                this.analysisLogs = [];
                this.lastLogCount = 0;  // 重置日志计数
                console.log('日志已清空，重置计数器');
            },

            // 启动实时日志轮询
            async startLogPolling() {
                if (!this.currentTaskId) return;
                
                // 清除之前的定时器
                await this.stopLogPolling();
                
                // 首先获取当前服务器的日志数量，设置正确的起始计数
                try {
                    const response = await axios.get(`/api/eda/task/${this.currentTaskId}/logs`);
                    if (response.data && response.data.logs) {
                        this.lastLogCount = response.data.logs.length;
                        console.log(`初始化日志计数: ${this.lastLogCount}`);
                    }
                } catch (error) {
                    console.warn('初始化日志计数失败:', error.message);
                }
                
                // 每2秒轮询一次日志
                this.logPollingTimer = setInterval(async () => {
                    await this.fetchRealtimeLogs();
                }, 2000);
            },

            // 停止实时日志轮询
            async stopLogPolling() {
                if (this.logPollingTimer) {
                    clearInterval(this.logPollingTimer);
                    this.logPollingTimer = null;
                }
                
                // 注释掉这里的强制获取，避免日志顺序混乱
                // 现在在任务完成时会主动获取最终日志
                // if (this.currentTaskId) {
                //     console.log('停止轮询后强制获取最终日志...');
                //     await this.fetchRealtimeLogs();
                // }
            },

            // 获取实时日志
            async fetchRealtimeLogs() {
                if (!this.currentTaskId) return;
                
                try {
                    const response = await axios.get(`/api/eda/task/${this.currentTaskId}/logs`);
                    console.log('获取日志响应:', response.data);
                    
                    if (response.data && response.data.logs) {
                        const serverLogs = response.data.logs;
                        console.log(`服务器日志数量: ${serverLogs.length}, 本地计数: ${this.lastLogCount}`);
                        
                        // 只添加新的日志条目
                        if (serverLogs.length > this.lastLogCount) {
                            const newLogs = serverLogs.slice(this.lastLogCount);
                            console.log('新增日志:', newLogs);
                            
                            newLogs.forEach(log => {
                                // 检查是否已存在相同的日志（避免重复）
                                const exists = this.analysisLogs.some(existingLog => 
                                    existingLog.timestamp === log.timestamp && 
                                    existingLog.message === log.message
                                );
                                
                                if (!exists) {
                                    this.analysisLogs.push({
                                        type: log.type,
                                        message: log.message,
                                        timestamp: log.timestamp  // 直接使用服务器时间戳
                                    });
                                    console.log('添加日志:', log);
                                }
                            });
                            
                            this.lastLogCount = serverLogs.length;
                            
                            // 自动滚动到底部
                            this.$nextTick(() => {
                                const logContainer = this.$refs.logContainer;
                                if (logContainer) {
                                    logContainer.scrollTop = logContainer.scrollHeight;
                                }
                            });
                        }
                    }
                } catch (error) {
                    // 静默处理轮询错误，避免干扰用户体验
                    console.warn('获取实时日志失败:', error.message);
                }
            },

            // ========== 格式化方法 ==========
            formatNumber(row, column, cellValue) {
                if (typeof cellValue === 'number') {
                    return cellValue.toFixed(3);
                }
                return cellValue || '--';
            },

            formatDuration(row, column, cellValue) {
                if (typeof cellValue === 'number') {
                    return cellValue.toFixed(1);
                }
                return cellValue || '--';
            },

            formatPercentage(row, column, cellValue) {
                if (typeof cellValue === 'number') {
                    return (cellValue).toFixed(2);
                }
                return cellValue || '--';
            },

            formatQuality(row, column, cellValue) {
                if (typeof cellValue === 'number') {
                    const percentage = (cellValue * 100).toFixed(1);
                    let level = '差';
                    if (cellValue >= 0.9) level = '优秀';
                    else if (cellValue >= 0.8) level = '良好';
                    else if (cellValue >= 0.7) level = '一般';
                    return `${percentage}% (${level})`;
                }
                return cellValue || '--';
            },

            formatFileSize(bytes) {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            },

            // ========== 表格交互方法 ==========
            handleSortChange(sortInfo) {
                console.log('排序变化:', sortInfo);
            },

            getStatusType(status) {
                const statusMap = {
                    'waiting': 'info',
                    'analyzing': 'warning',
                    'completed': 'success',
                    'error': 'danger'
                };
                return statusMap[status] || 'info';
            },

            getStatusText(status) {
                const statusMap = {
                    'waiting': '等待中',
                    'analyzing': '分析中',
                    'completed': '已完成',
                    'error': '分析失败'
                };
                return statusMap[status] || '未知';
            },

            // ========== 列管理方法 ==========
            resetColumns() {
                this.selectedColumns = [...EDAAnalysisConfig.defaultColumns];
            },
            
            applyColumnSettings() {
                this.showColumnManager = false;
            },
            
            // 按分类切换列显示
            toggleCategoryColumns(category, checked) {
                const categoryColumns = this.allColumns
                    .filter(col => col.category === category)
                    .map(col => col.prop);
                
                if (checked) {
                    categoryColumns.forEach(prop => {
                        if (!this.selectedColumns.includes(prop)) {
                            this.selectedColumns.push(prop);
                        }
                    });
                } else {
                    this.selectedColumns = this.selectedColumns.filter(prop => 
                        !categoryColumns.includes(prop)
                    );
                }
            },
            
            // 检查分类是否全选
            isCategoryFullySelected(category) {
                const categoryColumns = this.allColumns
                    .filter(col => col.category === category)
                    .map(col => col.prop);
                return categoryColumns.every(prop => this.selectedColumns.includes(prop));
            },
            
            // 检查分类是否部分选中
            isCategoryIndeterminate(category) {
                const categoryColumns = this.allColumns
                    .filter(col => col.category === category)
                    .map(col => col.prop);
                const selectedCount = categoryColumns.filter(prop => 
                    this.selectedColumns.includes(prop)
                ).length;
                return selectedCount > 0 && selectedCount < categoryColumns.length;
            },

            // ========== 导出方法 ==========
            async exportResults(format) {
                if (this.analysisResults.length === 0) {
                    ElMessage.warning('没有可导出的数据');
                    return;
                }

                if (!this.currentTaskId) {
                    ElMessage.error('没有有效的任务ID');
                    return;
                }

                try {
                    const response = await axios.get(`/api/eda/export/${this.currentTaskId}/${format}`, {
                        responseType: 'blob'
                    });

                    const blob = new Blob([response.data]);
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    
                    const contentDisposition = response.headers['content-disposition'];
                    let filename = `EDA分析结果_${new Date().toISOString().slice(0, 10)}.${format}`;
                    if (contentDisposition) {
                        const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                        if (filenameMatch) {
                            filename = filenameMatch[1];
                        }
                    }
                    
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);

                    ElMessage.success(`导出${format.toUpperCase()}文件成功`);
                } catch (error) {
                    ElMessage.error(`导出失败: ${error.message}`);
                }
            },

            exportToCSV() {
                this.exportResults('csv');
            },

            exportToExcel() {
                this.exportResults('excel');
            },

            // ========== 分析配置方法 ==========
            getAlgorithmInfo(algorithm) {
                const info = {
                    'brainhorm': {
                        name: 'BrainHorm算法',
                        description: '使用改进的EDA处理算法，支持自定义参数配置，适合精细化分析'
                    },
                    'neurokit2': {
                        name: 'NeuroKit2算法', 
                        description: '基于NeuroKit2库的标准EDA处理方法，使用成熟的信号处理技术'
                    }
                };
                return info[algorithm] || { name: '未知算法', description: '算法信息不可用' };
            }
        },

        mounted() {
            // 初始化页面菜单和标题
            const pageName = 'eda-analysis.html';
            if (window.MenuConfig) {
                window.MenuConfig.initializePageMenu(pageName);
            } else if (typeof initializePageMenu === 'function') {
                initializePageMenu(pageName);
            }

            // 初始化通用header
            window.CommonHeader.initHeader('header-container');

            // 初始化默认显示的列
            this.selectedColumns = [...EDAAnalysisConfig.defaultColumns];

            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                if (window.innerWidth > 575) {
                    this.sidebarShow = false;
                }
            });
        },

        // 组件销毁前清理定时器
        async beforeDestroy() {
            await this.stopLogPolling();
        }
    });

    return app;
}

// 初始化应用
function initEDAAnalysisApp() {
    const app = createEDAAnalysisApp();
    
    // 注册图标并挂载应用
    window.IconsConfig.registerIcons(app);
    app.use(ElementPlus).mount('#app');
    
    return app;
}